import WorkerPool from "./workerPool";
import path from "path";
import lz from "lz-string";

console.log("lz.compressToUTF16: ", lz.compressToUTF16); // 这行输出是为了让 server 端包含 lz-string 的依赖

// const compressWorkerPath = path.resolve("./server/utils/compressWorker.js");
// const decompressWorkerPath = path.resolve("./server/utils/decompressWorker.js");

// 获取项目根目录
const projectRoot = process.cwd();
// console.log("获取项目根目录", projectRoot);
let compressWorkerPath = "";

try {
  // 构建 Worker 脚本的绝对路径
  const projectRoot1 = path.resolve(
    projectRoot,
    process.env.NODE_ENV != "development" ? ".output/public" : "./public",
    "worker",
    "compressWorker.mjs"
  );
  // console.log("现在 获取项目根目录", projectRoot1);
  compressWorkerPath = projectRoot1;
} catch (error) {
  console.error("worker 路径错误", error);
}

let decompressWorkerPath = "";
try {
  // 构建 Worker 脚本的绝对路径
  const projectRoot2 = path.resolve(
    projectRoot,
    process.env.NODE_ENV != "development" ? ".output/public" : "./public",
    "worker",
    "decompressWorker.mjs"
  );

  decompressWorkerPath = projectRoot2;
} catch (error) {
  console.error("worker 路径错误", error);
}

const compressWorkerPool = new WorkerPool(compressWorkerPath);
const decompressWorkerPool = new WorkerPool(decompressWorkerPath);

class LzStringWorkerAdapter {
  constructor(options = {}) {
    this.options = options;
    // 底层适配器，可以是 LokiJS 内置的适配器，例如 LokiFsAdapter
    this.mode = "normal";

    if (options.adapter) {
      this.adapter = options.adapter;
    } else if (typeof window !== "undefined") {
      // 浏览器环境，使用 IndexedDB
      this.adapter = new LokiIndexedAdapter();
      this.mode = "browser";
    } else {
      // Node.js 环境，使用文件系统适配器
      const Loki = require("lokijs");
      this.adapter = new Loki.LokiFsAdapter();
      this.mode = "node";
    }
  }

  saveDatabase(dbname, dbstring, callback) {
    // 使用 worker 进行数据压缩
    compressWorkerPool
      .runTask(dbstring)
      .then((compressedData) => {
        // 将压缩后的数据传递给底层适配器进行保存
        this.adapter.saveDatabase(dbname, compressedData, callback);
      })
      .catch((err) => {
        console.log("compressWorkerPool Err ❌", err);
        callback(err);
      });
  }

  loadDatabase(dbname, callback) {
    // 从底层适配器加载数据
    this.adapter.loadDatabase(dbname, (err, compressedData) => {
      if (err && err instanceof Error) {
        console.error("数据加载 Err ❌", err);
        callback(err);
        return;
      }

      // 如果没有数据（文件不存在等），返回空数据库
      if (!compressedData && !err) {
        console.error(err, "数据为空 返回空数据", compressedData);
        callback(null, compressedData);
        return;
      }

      // 使用 worker 进行数据解压缩
      decompressWorkerPool
        .runTask(compressedData || err)
        .then((dbstring) => {
          // console.log("解压之后的数据:", dbstring);

          callback(dbstring); // lokijs 2600 行
        })
        .catch((err) => {
          console.log("❌ worker 进行数据解压缩 Err:", err);
          callback(err);
        });
    });
  }

  // 实现其他适配器方法
  deleteDatabase(dbname, callback) {
    if (typeof this.adapter.deleteDatabase === "function") {
      this.adapter.deleteDatabase(dbname, callback);
    } else {
      callback(new Error("Underlying adapter does not support deleteDatabase"));
    }
  }

  close(callback) {
    if (typeof this.adapter.close === "function") {
      this.adapter.close(callback);
    } else {
      if (callback) callback(null);
    }
  }
}

export default LzStringWorkerAdapter;
